using System;
using HCore.IOC.Context.Event;
using HCore.IOC.Context.Event.Attr;
using HCore.IOC.Context.Stereotype;
using HCore.Tests.Runtime.DianDianDian.Event;

namespace HCore.Tests.Runtime.DianDianDian.System
{
    public interface ICountDownSystem
    {
        /// <summary>
        ///     当前剩余时间，单位：秒
        /// </summary>
        int GetCurrentRemainSeconds();

        void Update();
    }

    [Component]
    public class CountDownSystem : EventPublisher, ICountDownSystem
    {
        private static readonly object _LOCK = new();
        private DateTime mGameStartTime = DateTime.Now;
        private bool mStarted;

        public int GetCurrentRemainSeconds()
        {
            var time = 10 - (int)(DateTime.Now - mGameStartTime).TotalSeconds;
            return time <= 0 ? 0 : time;
        }

        public void Update()
        {
            lock (_LOCK)
            {
                if (!mStarted) return;
                mStarted = false;
            }

            if (DateTime.Now - mGameStartTime <= TimeSpan.FromSeconds(10)) return;
            PublishEvent(new CountDownEndEvent());
        }

        [EventListener]
        private void OnGameStartEvent(GameStartEvent @event)
        {
            mStarted = true;
            mGameStartTime = DateTime.Now;
        }

        [EventListener]
        private void OnGamePassEvent(GamePassEvent @event)
        {
            mStarted = false;
        }
    }
}